﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Topro.Application.Impl
{
    using Topro.Application.Interface;

    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Setting;
    using Topro.Entity.Response.Setting;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 设置业务接口实现
    /// </summary>
    public class SettingServiceImpl: SettingService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public SettingServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public SettingResponse Get(int id)
        {
            return _db.DbConnection.QueryFirst<SettingResponse>("select * from setting where Id=@Id", new { Id = id });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="type">编号</param>
        /// <returns></returns>
        public List<SettingResponse> GetByType(int type)
        {
            return _db.DbConnection.Query<SettingResponse>("select * from setting where Type=@Type", new { Type = type }).ToList();
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveIQS(SaveSettingRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };


            try
            {
                if (request.Id > 0)
                {

                    var setting = _db.DbConnection.QueryFirst<Setting>("select * from setting where Id=@Id", new { Id = request.Id });
                    if (setting == null)
                    {
                        throw new Exception("设置记录不存在.");
                    }

                    setting.CreatedDate = DateTime.Now;

                    _db.DbConnection.Update<Setting>(setting);

                    response.Success = true;
                }
                else
                {
                    //var iqsExist = _dbSession.DbConnection.Query<IQS>("SELECT * FROM iqs WHERE Name=@Name", new { Name = request.Name });
                    //if (iqsExist != null && iqsExist.Any())
                    //{
                    //    throw new Exception("IQS已存在.");
                    //} 

                    var setting = new Setting()
                    {
                        CreatedDate = DateTime.Now
                    };

                    //新增
                    var resultId = _db.DbConnection.Insert<Setting>(setting);

                    if (resultId <= 0)
                    {
                        throw new Exception("新增设备失败.");
                    }

                    response.Success = true;
                }
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<SettingQueryResponse> GetPager(SettingQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,Name,Value,Status,DisplayOrder,CreatedDate";
            var tableName = "setting";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            //if (!string.IsNullOrEmpty(query.Name))
            //{
            //    where += string.Format(" And Name like'%{0}%'", query.Name);
            //}
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);

            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<SettingQueryResponse>();

                return new PagedList<SettingQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.PageIndex,
                    TotalCount = count
                };
            }
        }
    }
}
